﻿
namespace ShpMerger
{
    public class Header
    {
        private int fileCode;
        private int unUsed1;
        private int unUsed2;
        private int unUsed3;
        private int unUsed4;
        private int unUsed5;
        private int fileLenth;
        private int fileVerion;
        private int shapeType;
        private BoundingBox boundingBox;

        public Header()
        {
            fileCode = -1;
            unUsed1 = 0;
            unUsed2 = 0;
            unUsed3 = 0;
            unUsed4 = 0;
            unUsed5 = 0;
            fileLenth = 0;
            fileVerion = 0;
            shapeType = 0;
            boundingBox = new BoundingBox();
        }

        public void Read(ExtendBinaryReader extendBinaryReader)
        {
            // Read int32 using big Endian.
            fileCode = extendBinaryReader.ReadInt32UsingBigEndian();
            unUsed1 = extendBinaryReader.ReadInt32UsingBigEndian();
            unUsed2 = extendBinaryReader.ReadInt32UsingBigEndian();
            unUsed3 = extendBinaryReader.ReadInt32UsingBigEndian();
            unUsed4 = extendBinaryReader.ReadInt32UsingBigEndian();
            unUsed5 = extendBinaryReader.ReadInt32UsingBigEndian();
            fileLenth = extendBinaryReader.ReadInt32UsingBigEndian();

            //Read int32  using little Endian.
            fileVerion = extendBinaryReader.ReadInt32();
            shapeType = extendBinaryReader.ReadInt32();
            boundingBox.Read(extendBinaryReader);
        }

        public void Write(ExtendBinaryWriter extendBinaryWriter)
        {
            // Write int32 using big Endian.
            extendBinaryWriter.WriteUsingBigEndian(fileCode);
            extendBinaryWriter.WriteUsingBigEndian(unUsed1);
            extendBinaryWriter.WriteUsingBigEndian(unUsed2);
            extendBinaryWriter.WriteUsingBigEndian(unUsed3);
            extendBinaryWriter.WriteUsingBigEndian(unUsed4);
            extendBinaryWriter.WriteUsingBigEndian(unUsed5);
            extendBinaryWriter.WriteUsingBigEndian(fileLenth);

            // Write int32  using little Endian.
            extendBinaryWriter.Write(fileVerion);
            extendBinaryWriter.Write(shapeType);
            boundingBox.Write(extendBinaryWriter);
        }

        public void Merge(Header header)
        {        
            if (fileCode == -1)
            {
                fileCode = header.fileLenth;
                fileVerion = header.fileVerion;
                shapeType = header.shapeType;
            }

            // Two shapefiles after merge relive one header.
            fileLenth = fileLenth + header.fileLenth - 50;

            boundingBox.Merge(header.boundingBox);    
        }
    }    
}
